import {
    computed,
    defineComponent,
    nextTick,
    onMounted,
    reactive,
    ref,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import clipboard from "clipboardy";
import { ElMessage, ElMessageBox } from "element-plus";
import QrCodeGenerator from "@/components/qrcode/clientEntry.vue";
import * as api from "@/services/api";
import { updateNetorkInfo } from "@/share/constants";

export default {
    components: {
        QrCodeGenerator, // 注册组件
    },

    setup() {
        const router = useRouter();

        // 分割筛选项间的间距，如「全部」、与「未开始」之间的间距
        const projectGutter = ref(20);
        // 过滤筛选状态 全部 0、未开始 1、进行中 2、已结束 3
        const activeFilter = ref("0");

        // 显示列表中的活动；即筛选查询的结果
        const activities = ref([]);

        const deleteConfirmVisiable = ref(false);
        const createDialogVisiable = ref(false);
        const recycleVisiable = ref(false);

        const loading = ref(false);

        // 当前选中要处理的活动
        const currentActivity = ref({
            id: "",
            name: "",
        });

        // 表单数据
        const createingActivity = ref({
            name: "", // 活动名称（必填）
            serial: "", // 活动编号（可选）
            activity_time: "", // 活动开始时间（可选）
            activity_end: "", // 活动结束时间（可选）
            intro: "", // 活动描述（可选）
            sign_amount: 0, // 签到数量（默认0）
            is_deleted: 1, // 软删除标记（默认1=未删除）
            state: 1, // 活动状态（默认1=未开始）
        });

        const activitySearchModel = ref(""); // 搜索内容
        const activitySearchType = ref(1); // 搜索类型

        // 搜索类型选项
        const activitySearchTypeOptions = ref([
            {
                label: "名称",
                value: 1,
            },
            {
                label: "编号",
                value: 2,
            },
        ]);

        // 创建活动表单规则
        const rules = {
            name: [
                { required: true, message: "请输入活动名称", trigger: "blur" },
                {
                    min: 2,
                    max: 50,
                    message: "长度在2到50个字符",
                    trigger: "blur",
                },
            ],
        };

        const searchTypeSelected = () => {
            console.log("activity search type::", activitySearchType);
        };

        // 删除活动
        const deleteCurrentActivity = async (id) => {
            // 软删除
            if (recycleVisiable.value === false) {
                await api.deleteAcvitity(id);
            }

            if (recycleVisiable.value === true) {
                await api.deleteAcvitity(id);
            }
            currentActivity.value = { id: "", name: "" };
            router.go(0);
        };

        // 按钮组按钮被点击
        const handleButtonClick = async (action, id = 0) => {
            currentActivity.value =
                activities.value.find((item) => item.id === id) || {};

            if (
                currentActivity.value.is_deleted === 2 &&
                !["data", "delete"].includes(action)
            ) {
                ElMessage.error("活动已删除");
                return false;
            }
            // 跳到「活动设置」页
            if (action === "settings") {
                router.push("/activity-setting");
            }
            // 跳到「大屏设置」页
            if (action === "screen") {
                router.push("/screen-setting");
            }
            // 跳到「大屏设置」页
            if (action === "client") {
                router.push("/client-setting");
            }

            if (action == "data") {
                router.push("/activity-data");
            }

            if (action == "delete") {
                deleteConfirmVisiable.value = true;
            }
        };

        const fetchAllActivities = async (params) => {
            // console.log('params::::', params);
            setTimeout(() => {
                loading.value = true;
            }, 500);
            const resp = await api.getActivities(params);
            // console.log('查询的结果是：：', resp.data)
            activities.value = resp.data.activities;
            setTimeout(() => {
                loading.value = false;
            }, 500);
        };

        // 关闭删除确认对话框的处理
        const handleCloseDelConfirm = () => {
            // ElMessageBox.confirm('Are you sure to close this dialog?')
            //     .then(() => {
            //         done()
            //     })
            //     .catch(() => {
            //         // catch error
            //     })
        };

        // 关闭创建活动对话框的处理
        const handleCloseCreateDialog = () => {};

        // 关闭二维码对话框的处理
        const handleCloseQRConfirm = () => {
            clientQRcodeVisiable.value = false;
        };

        const showRecycle = () => {
            recycleVisiable.value = true;
            // console.log('recycleVisiable::', recycleVisiable.value)
            fetchAllActivities({ is_deleted: 2 });
        };

        const RANGE_MAP = {
            all: "0",
            notStarted: "1",
            running: "2",
            over: "3",
        };

        // 按状态获取活动
        const getActivitiesByState = (range) => {
            activeFilter.value = RANGE_MAP[range] ?? activeFilter.value;
            recycleVisiable.value = false;

            const state = Number(activeFilter.value); // 转为数字类型

            const p = state ? { state: state } : {};
            // console.log('p', p);

            fetchAllActivities(p);
        };

        // 重置正在创建活动的数据
        const createingActivityRset = () => {
            createingActivity.value = {
                name: "", // 活动名称（必填）
                serial: "", // 活动编号（可选）
                activity_time: "",
                activity_end: "",
                intro: "", // 活动描述（可选）
                sign_amount: 0, // 签到数量（默认0）
                is_deleted: 1, // 软删除标记（默认1=未删除）
                state: 1, // 活动状态（默认1=未开始）
            };
        };

        // 创建活动方法
        const createActivity = async () => {
            try {
                // 处理空时间（设置为当前时间）
                if (!createingActivity.value.activity_time) {
                    createingActivity.value.activity_time =
                        new Date().toISOString();
                }

                if (!createingActivity.value.name) {
                    ElMessage.error("活动名称不可少");
                    return false;
                }

                // 时间校验
                if (!validateActivityTime()) {
                    return false;
                }

                // TODO::校验活动状态
                const now = new Date();
                const startTime = new Date(
                    createingActivity.value.activity_time,
                );
                const endTime = new Date(createingActivity.value.activity_end);

                createingActivity.value.state =
                    startTime > now
                        ? 1 // 未开始
                        : endTime > now
                          ? 2 // 进行中
                          : 3; // 已结束

                // 调用API
                await api.createAcvitity(createingActivity.value);
                ElMessage.success("创建成功");
                createDialogVisiable.value = false;
                // 刷新列表
                fetchAllActivities();
                createingActivityRset();
            } catch (error) {
                ElMessage.error("创建失败：" + error.message);
            }
        };

        // 限制日期选择范围
        const disabledDate = (time) => {
            // 获取当前时间（去掉毫秒）
            const now = new Date();
            now.setHours(0, 0, 0, 0);

            // 如果选择的日期在今天之前，则禁用
            return time.getTime() < now.getTime();
        };

        // 执行搜索
        const handleSearch = () => {
            let params = {};

            const obj = activitySearchTypeOptions.value.reduce((acc, cur) => {
                acc[cur.label] = cur.value;
                return acc;
            }, {});

            if (activitySearchModel.value && activitySearchType.value === 1) {
                params["name"] = activitySearchModel.value;
            }

            if (activitySearchModel.value && activitySearchType.value === 2) {
                params["serial"] = activitySearchModel.value;
            }

            if (recycleVisiable.value === true) {
                params["is_deleted"] = 2;
            }

            const state = Number(activeFilter.value); // 转为数字类型
            if (state) {
                params["state"] = state;
            }

            // 这里调用你的搜索API
            fetchAllActivities(params);
        };

        function formatDateTimeToDate(datetime) {
            if (!datetime) return "";
            return datetime.split(" ")[0];
        }

        const validateActivityTime = () => {
            const start = new Date(createingActivity.value.activity_time);
            const end = new Date(createingActivity.value.activity_end);

            // 精确到秒的比较
            if (start && end && end.getTime() <= start.getTime()) {
                ElMessage.error("结束时间必须晚于开始时间");
                return false;
            }
            return true;
        };

        // 开始时间禁用规则
        const disabledStartDate = (time) => {
            return time.getTime() < Date.now() - 1000; // 精确到秒，禁用当前秒之前的所有时间
        };

        const disabledStartTime = computed(() => {
            return (date) => {
                const now = new Date();
                if (date.toDateString() === now.toDateString()) {
                    return {
                        disabledHours: () => range(0, now.getHours()),
                        disabledMinutes: (hour) =>
                            hour === now.getHours()
                                ? range(0, now.getMinutes())
                                : [],
                        disabledSeconds: (hour, minute) =>
                            hour === now.getHours() &&
                            minute === now.getMinutes()
                                ? range(0, now.getSeconds())
                                : [],
                    };
                }
                return {};
            };
        });

        // 结束时间禁用规则（必须晚于开始时间）
        const disabledEndDate = (time) => {
            if (!createingActivity.value.activity_time)
                return time.getTime() < Date.now();
            const startTime = new Date(createingActivity.value.activity_time);
            return time.getTime() < startTime.getTime();
        };

        const disabledEndTime = computed(() => {
            return (date) => {
                if (!createingActivity.value.activity_time) return {};
                const startTime = new Date(
                    createingActivity.value.activity_time,
                );

                if (date.toDateString() === startTime.toDateString()) {
                    return {
                        disabledHours: () => range(0, startTime.getHours()),
                        disabledMinutes: (hour) =>
                            hour === startTime.getHours()
                                ? range(0, startTime.getMinutes())
                                : [],
                        disabledSeconds: (hour, minute) =>
                            hour === startTime.getHours() &&
                            minute === startTime.getMinutes()
                                ? range(0, startTime.getSeconds())
                                : [],
                    };
                }
                return {};
            };
        });

        // 辅助函数
        const range = (start, end) => {
            const result = [];
            for (let i = start; i < end; i++) {
                result.push(i);
            }
            return result;
        };

        // 新增显示控制状态
        const showQRCode = ref(true);
        const qrGeneratorRef = ref(null);
        const networkInfo = ref({
            ip: "",
            serverPort: "",
            clientPort: "",
            hostname: "",
            email: "",
            serial: "",
        });
        // 是否显示用户端二维码
        const clientUrl = ref("");
        const clientQRcodeVisiable = ref(false);

        // 切换显示状态
        const toggleQRCode = () => {
            showQRCode.value = !showQRCode.value;
        };

        // 强制刷新二维码
        const refreshQRCode = () => {
            if (qrGeneratorRef.value) {
                qrGeneratorRef.value.refresh();
            }
        };

        // 「客户端入口」显示客户端二维码
        const showClientQRcode = async (aid) => {
            clientQRcodeVisiable.value = true;

            networkInfo.value = await updateNetorkInfo();
            console.log("system-info get ipaddress::", networkInfo.value);

            const hostIP = networkInfo.value.ip;
            const clientIP = networkInfo.value.clientPort;

            clientUrl.value = `http://${hostIP}:${clientIP}/#/client/signature?aid=${aid}&st=${networkInfo.value.serverPort}`;
        };

        // 拷贝客户端二维码地址
        const copyClientQrcode = async () => {
            if (!clientUrl.value) return;

            try {
                await clipboard.write(clientUrl.value);

                ElMessage.success("复制成功!");
            } catch (error) {
                console.error("复制失败,准备使用替代方案:", error);
                // 备用方案：使用execCommand
                const textarea = document.createElement("textarea");
                textarea.value = clientUrl.value;
                document.body.appendChild(textarea);
                textarea.select();
                try {
                    document.execCommand("copy");
                    ElMessage.success("复制成功! (备用方法)");
                } catch (err) {
                    console.error("备用复制方法失败:", err);
                    ElMessage.error("复制失败，请手动复制内容");
                } finally {
                    document.body.removeChild(textarea);
                }
            }
        };

        onMounted(() => {
            fetchAllActivities();
            console.log("挂载后的活动::", activities.value);
        });

        return {
            loading,
            formatDateTimeToDate,
            disabledDate,
            activities,
            activeFilter,
            projectGutter,
            deleteConfirmVisiable,
            createDialogVisiable,
            recycleVisiable,
            currentActivity,
            createingActivity,
            searchTypeSelected,
            activitySearchModel,
            activitySearchType,
            activitySearchTypeOptions,
            handleSearch,
            deleteCurrentActivity,
            // 弹出客户端入口二维码
            showClientQRcode,
            clientQRcodeVisiable,
            handleCloseQRConfirm,
            clientUrl,
            showQRCode,
            copyClientQrcode,

            handleButtonClick,
            showRecycle,
            getActivitiesByState,
            createActivity,
            handleCloseDelConfirm,
            handleCloseCreateDialog,
        };
    },
};
